package my.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.json.Json;
import com.jfinal.plugin.activerecord.Page;
import my.common.Util;
import my.interceptor.LoginInterceptor;
import my.model.Message;
import my.model.User;
import my.service.MessageService;
import sun.rmi.runtime.Log;

import java.util.List;
import java.util.Objects;

/**
 * Created by Administrator on 2017/4/13 0013.
 */
public class MessageController extends Controller {
    public void index() {
        list();
    }

    public void list() {
        renderFreeMarker("list-new.ftl");
    }

    public void json() {
        int start = getParaToInt("start", 0);
        int length = getParaToInt("length", 10);
        int draw = getParaToInt("draw", 1);
        int page = start / length + 1;

        Page<Message> messagePage = MessageService.paginateAllMessageDetail(page, length);
        setAttr("data", messagePage.getList());
        setAttr("draw", draw);
        setAttr("recordsTotal", messagePage.getTotalRow());  //获得总记录数
        setAttr("recordsFiltered", messagePage.getTotalRow());

        renderJson();
//        List<Message> messages = MessageService.getAllMessageDetail();
//        renderJson(messages);
    }

    public void save() {
        Message message = new Message();
        String title = getPara("message.title");
        String content = getPara("message.content");
        User user = getSessionAttr("user");
        message.setTitle(title);
        message.setUserId(user.getId());
        message.setContent(content);
        message.save();
        redirect("/message/list");
    }

    @Before(LoginInterceptor.class)
    public void create() {
        renderFreeMarker("create-new.ftl");
    }

    @Before(LoginInterceptor.class)
    public void delete() {
        User loginUser = (User) getSessionAttr("user");
        int id = getParaToInt(0, -1);

        boolean success = MessageService.deleteMessageById(loginUser.getId(), id);
        renderJson(Util.ajaxJson(success, success ? "删除成功" : "删除失败"));

//        int messageId = getParaToInt("messageId");
//        Message message = MessageService.getMessageById(messageId);
//        message.delete();
//
//        renderJson();
    }

    @Before(LoginInterceptor.class)
    public void update() {
        Message message = getModel(Message.class, "message", true);
        Message findMessage = MessageService.getMessageById(message.getId());
        User loginUser = getSessionAttr("user");
        boolean success = false;
        if (findMessage.getUserId() == loginUser.getId())
            success = MessageService.updateMessage(message);
        renderJson(Util.ajaxJson(success, success ? "编辑成功" : "编辑失败"));
    }
}
